import {
  getAllTerminal,

} from '../../../services/api/menber';
import {
  getCategoryList,
  getCategoryDetail
} from '../../../services/category/index';
import {
  agengCreatOrder,
  orderDetail
} from '../../../services/api/order'
import Toast from 'tdesign-miniprogram/toast/index';

// const defaultImg = require('../../../assets/1.gif')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customerName: '',
    popvisible: false,
    popvisible2: false,
    customerId: '',
    userList: [],
    goods: "",
    isEdit: false,
    defaultImg: "https://img1.baidu.com/it/u=415449740,540746270&fm=253&fmt=auto&app=138&f=GIF?w=500&h=500",
    choiseList: [],
    formInfo: {
      customerKid: "",
      memo: "",
      productList: []
    },
    dataList: [],
    childList: [],
    pageNo: 1,
    pageSize: 10,
    currentActive: 0,
    orderId: ''
  },
  init() {
    getCategoryList({}).then((res) => {
      this.setData({
        dataList: res.data,
      });
      if (res.data.length > 0) {
        this.getChildList(res.data[0]);
      }
    });
  },
  getChild(e) {
    this.onReset();
    const {
      item,
      index
    } = e.target.dataset;
    getCategoryDetail({
      param: {
        classifyId: item.kid,
        shelveFlag: 1,
      },
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize,
    }).then((res) => {
      if (res.data.entities) {
        for (let i = 0; i < res.data.entities.length; i++) {
          for (let j = 0; j < this.data.choiseList.length; j++) {
            if (this.data.choiseList[j].kid == res.data.entities[i].kid) {
              res.data.entities[i].selected = true;
              continue;
            }
          }
        }
      }
      this.setData({
        childList: res.data.entities,
        currentActive: index,
      });
    });
  },
  getChildList(item) {
    this.onReset();
    getCategoryDetail({
      param: {
        classifyId: item.kid,
        shelveFlag: 1,
      },
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize,
    }).then((res) => {

      this.setData({
        childList: res.data.entities,
      });
    });
  },
  onReset() {
    this.setData({
      pageNo: 1,
      pageSize: 10,
    });
  },
  choise(e) {
    let index = e.currentTarget.dataset.index;
    let childList = this.data.childList;
    let temp = JSON.parse(JSON.stringify(this.data.choiseList));
    childList[index].selected = !childList[index].selected;
    if (childList[index].selected) {
      temp.push(childList[index]);
      for (let i = 0; i < temp.length; i++) {
        for (let j = i + 1; j < temp.length; j++) {
          if (temp[i].kid == temp[j]) {
            temp.splice(j, 1)
            j--;
          }
        }
      }
    } else {
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].kid == childList[index].kid) {
          temp.splice(i, 1);
          break;
        }
      }
    }
    this.setData({
      childList,
      choiseList: temp,

    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    let agentId = options.orderId;
    this.init();
    if (options.customerId) {
      //  已制定好不许要选择客户
      this.setData({
        customerId: options.customerId
      })
    }
    if (options.isEdit) {
      this.getDetailData(options.kid)
      return
    }
    this.initUser(agentId);
  },
  async getDetailData(kid) {
    let {
      code,
      data
    } = await orderDetail({
      kid
    });
    this.setData({
      isEdit: true,
      customerName: data.customerName,
      ['formInfo.memo']: data.memo,
      ['formInfo.productList']: data.productList.map((el) => {
        let list = el.picSmall.split(',');
        console.log(list, 'list')
        return {
          ...el,
          pic: el.picSmall ? el.picSmall.split(',')[0] : ''
        }
      }),
    })
  },

  async initUser(id) {
    let {
      code,
      data
    } = await getAllTerminal({
      pageNo: 1,
      pageSize: 10,
      param: {
        agentUserId: id
      }
    })
    this.setData({
      userList: data.entities
    });
  },
  async confirmDispatch(e) {
    if (!this.data.formInfo.customerKid) {
      Toast({
        selector: '#t-toast',
        message: '请选择处理人员',
        icon: '',
        duration: 1000,
      });
      return
    }
    this.setData({
      popvisible: false
    });
  },
  clickCell() {
    if (this.data.isEdit) {
      return
    }
    this.setData({
      popvisible: true
    })

  },
  clickCellGoods() {
    this.setData({
      popvisible2: true
    })
  },
  // input 数据绑定
  onInputChange(e) {
    const key = e.currentTarget.dataset.key,
      value = e.detail.value;
    this.setData({
      [key]: value
    })
  },
  onpopChange(e) {
    const index = e.currentTarget.dataset.index;
    let list = this.data.formInfo.productList;
    let key = e.currentTarget.dataset.key;
    list[index][key] = e.detail.value;
  },

  onVisibleChange(e) {
    this.setData({
      popvisible: e.detail.visible,
    });
  },
  onVisibleChange2(e) {
    let temp = [];
    console.log(this.data.choiseList);

    for (let i = 0; i < this.data.choiseList.length; i++) {
      temp.push({
        picSmall: this.data.choiseList[i].picSmall.split(',')[0],
        pic: this.data.choiseList[i].picSmall.split(',')[0],
        productName: this.data.choiseList[i].productName,
        descLong: this.data.choiseList[i].desc_long,
        num: 1,
        couponPrice: '',
        unitPrice: "",
        productKid: this.data.choiseList[i].kid
      })
    }
    this.setData({
      popvisible2: e.detail.visible,
      'formInfo.productList': temp
    });

  },

  onChange(e) {
    console.log(e, 'e');
    this.data.userList.forEach((el) => {
      if (el.kid == e.detail.value) {
        this.setData({
          'formInfo.customerKid': e.detail.value,
          customerName: el.customerName
        })
      }
    })
  },
  async save() {
    if (!this.data.formInfo.customerKid && !this.data.customerId) {
      Toast({
        selector: '#t-toast',
        message: '请选择终端客户',
        icon: '',
        duration: 1000,
      });
      return
    }
    // if(!this.data.formInfo.memo){
    //   Toast({
    //     selector: '#t-toast',
    //     message: '请填写备注',
    //     icon: '',
    //     duration: 1000,
    //   });
    //   return
    // }
    let flag = false;
    this.data.formInfo.productList.forEach((el) => {
      if (!el.couponPrice || !el.unitPrice || !el.num) {
        flag = true
      }
    });
    if (flag) {
      Toast({
        selector: '#t-toast',
        message: '请完善订单信息',
        icon: '',
        duration: 1000,
      });
      return
    }
    let params = this.data.formInfo;
    let productList = this.data.formInfo.productList.map((el) => {
      return {
        ...el,
        couponPrice: el.couponPrice * 100,
        unitPrice: el.unitPrice * 100
      }
    });
    console.log(productList);
    let {
      code,
      data
    } = await agengCreatOrder({
      ...this.data.formInfo,
      productList,
      customerKid: this.data.formInfo.customerKid || this.data.customerId

    });
    if (data) {
      wx.navigateBack({
        delta: -1,
      })
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})